package org.example.JVM.ByteCode;

import org.example.JVM.ByteCode.Type.ClassFile;
import org.example.JVM.ByteCode.Util.ClassFileAnalysiser;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;

/**
 * @description: 将class文件读取到ByteBuffer并解析
 * @author: farprt
 * @create: 2022-11-13 13:57
 **/
public class ClassFileAnalysisMain {

    public static ByteBuffer readFile(String classFilePath) throws Exception {
        File file = new File(classFilePath);
        if (!file.exists()) {
            throw new Exception("file not exists!");
        }
        byte[] byteCodeBuf = new byte[4096];
        int length;
        try (InputStream in = new FileInputStream(file)) {
            length = in.read(byteCodeBuf);
        }
        if (length < 1) {
            throw new Exception("not read byte code");
        }
        //将字节数组包装为ByteBuffer
        return ByteBuffer.wrap(byteCodeBuf, 0, length).asReadOnlyBuffer();
    }

    public static void main(String[] args) throws Exception {
        ByteBuffer codeBuf=readFile("target/classes/org/example/App.class");
        ClassFile classFile= ClassFileAnalysiser.analysis(codeBuf);
        System.out.println(classFile.getMagic().toHexString());
    }
}